package cn.nfwx.tv.controller.me;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.nfwx.tv.R;
import cn.nfwx.tv.adapter.DownLoadingAdapter;
import cn.nfwx.tv.base.BaseFragment;
import cn.nfwx.tv.controller.DownloadM3u8Controller;
import cn.nfwx.tv.db.AppDatabase;
import cn.nfwx.tv.db.DownProgramDao;
import cn.nfwx.tv.db.DownProgramModel;
import cn.nfwx.tv.db.TsDao;
import cn.nfwx.tv.db.TsProgramModel;
import cn.nfwx.tv.events.PlayEvents;
import cn.nfwx.tv.fragment.me.MineAllFragment;
import cn.nfwx.tv.fragment.me.MineFragment;
import cn.nfwx.tv.helper.AccountHelper;
import cn.nfwx.tv.helper.DialogFragmentHelper;
import cn.nfwx.tv.helper.NetworkHelper;
import cn.nfwx.tv.helper.ThreadHelper;
import cn.nfwx.tv.helper.ValueCallback;
import cn.nfwx.tv.model.TvProgram;
import cn.nfwx.tv.util.LogUtil;
import cn.nfwx.tv.util.SharePrefUtil;
import cn.nfwx.tv.util.ToastUtil;
import cn.nfwx.tv.widget.LoadView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class MineTvDownloadController implements DownLoadingAdapter.OnCheckedChangeDelListener {
    private Context mContext;
    private MineAllFragment mFragment;
    private RecyclerView mRecyclerView;
    private LoadView mLoadView;
    private TwinklingRefreshLayout trl_mine;
    private View notDataView;
    private LinearLayout ll_mine_pause;
    private View v_spilt_pause;
    private TextView edit_mine_btn;
    private TextView tv_mine_select;

    private int currentSubTabSelect;

    private boolean isAllPause;

    private List<DownProgramModel> downingPrograms = new ArrayList<DownProgramModel>();
    private List<DownProgramModel> downedPrograms = new ArrayList<DownProgramModel>();

    private DownLoadingAdapter downLoadingAdapter;
    private ImageView btnView;
    private TextView all_text;


    public MineTvDownloadController(Context context, MineAllFragment fragment) {
        mContext = context;
        mFragment = fragment;
    }

    public void init(RecyclerView recyclerView, LoadView loadView, final TwinklingRefreshLayout trl_mine, View notDataView, LinearLayout ll_mine_pause, View v_spilt_pause, TextView edit_mine_btn) {
        mRecyclerView = recyclerView;
        mLoadView = loadView;
        this.trl_mine = trl_mine;
        this.notDataView = notDataView;
        this.ll_mine_pause = ll_mine_pause;
        this.v_spilt_pause = v_spilt_pause;
        this.edit_mine_btn = edit_mine_btn;

        if (downLoadingAdapter == null) {
            downLoadingAdapter = new DownLoadingAdapter();
        }
        mRecyclerView.setAdapter(downLoadingAdapter);
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);

        downLoadingAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Object o = adapter.getData().get(position);
                if (o instanceof DownProgramModel) {
                    DownProgramModel programModel = (DownProgramModel) o;
                    if (downLoadingAdapter.isDelete()) {
                        programModel.setCheck(!programModel.isCheck());
                        adapter.notifyItemChanged(position);
                    } else {
                        if (programModel.getStats() == DownProgramModel.STATS_SUCCESS) {
                            PlayEvents events = new PlayEvents(programModel.getLocalPath(), null, programModel.getProgramName(), 0);
                            if (mFragment.getParentFragment() instanceof MineFragment) {
                                MineFragment mineFragment = (MineFragment) mFragment.getParentFragment();
                                mineFragment.isBackEvent = false;
                                events.setFragment(PlayEvents.MINE);
                                events.setMePosition(MineFragment.POSITION_DOWNLOAD);
                                events.setTag("mineFragment");
                            }
                            EventBus.getDefault().post(events);
                        } else if (programModel.getStats() == DownProgramModel.STATS_PAUSE) {
                            if (!NetworkHelper.getInstance().hasConnection(mContext)) {
                                ToastUtil.show(mContext, R.string.nointernet, Toast.LENGTH_LONG);
                                return;
                            }
                            if (NetworkHelper.getInstance().isConnection4g(mContext)
                                    && !SharePrefUtil.getDownloadChoose(mContext)) {
                                ToastUtil.show(mContext, R.string.download_4g, Toast.LENGTH_LONG);
                                return;
                            }
                            DownloadM3u8Controller.getInstance().start(mContext, programModel.getDownloadUrl());
                        } else if (programModel.getStats() == DownProgramModel.STATS_DOWNLOADING
                                || programModel.getStats() == DownProgramModel.STATS_DEFAULT
                                || programModel.getStats() == DownProgramModel.STATS_WAIT) {
                            DownloadM3u8Controller.getInstance().pause(mContext, programModel.getDownloadUrl());
                        }
                    }
                }
            }
        });
        downLoadingAdapter.setOnCheckedChangeDelListener(this);
    }

    public void setCurrentSelect(int currentSelect) {
        currentSubTabSelect = currentSelect;
    }

    public void bindSubscriptData(ValueCallback<Boolean> valueCallback) {
        bindSubscriptData(currentSubTabSelect, valueCallback);
    }

    /**
     * 下载数据绑定
     *
     * @param position
     */
    public void bindSubscriptData(int position, final ValueCallback<Boolean> valueCallback) {
        if (position == 0) {
            final List downloadProgramList = new ArrayList<DownProgramModel>();
            ll_mine_pause.setVisibility(View.GONE);
            v_spilt_pause.setVisibility(View.GONE);
            edit_mine_btn.setVisibility(View.GONE);
            downLoadingAdapter.setNewData(new ArrayList<DownProgramModel>());

            if (downingPrograms.isEmpty()) {
                Observable.create(new ObservableOnSubscribe<DownProgramModel>() {
                    @Override
                    public void subscribe(ObservableEmitter<DownProgramModel> e) {
                        if (!AppDatabase.getInstance(mContext).isOpen()) {
                            e.onComplete();
                        }
                        DownProgramDao dao = AppDatabase.getInstance(mContext).programDao();
                        List<DownProgramModel> downProgramModels = dao.queryForAll();
                        for (DownProgramModel downProgramModel : downProgramModels) {
                            if (downProgramModel.getStats() == DownProgramModel.STATS_DEFAULT
                                    || downProgramModel.getStats() == DownProgramModel.STATS_DOWNLOADING
                                    || downProgramModel.getStats() == DownProgramModel.STATS_PAUSE
                                    || downProgramModel.getStats() == DownProgramModel.STATS_WAIT) {
                                e.onNext(downProgramModel);
                            }
                        }
                        e.onComplete();
                    }
                }).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .compose(mFragment.<DownProgramModel>bindToLifecycle())
                        .subscribe(new Observer<DownProgramModel>() {
                            @Override
                            public void onSubscribe(Disposable d) {
                            }

                            @Override
                            public void onNext(DownProgramModel downProgramModel) {
                                downloadProgramList.add(downProgramModel);
                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onComplete() {
                                trl_mine.finishRefreshing();
                                mLoadView.removeParentView(trl_mine);
                                if (downloadProgramList.isEmpty()) {
                                    edit_mine_btn.setVisibility(View.GONE);
                                    mFragment.hideBottom();
                                    downLoadingAdapter.setNewData(downloadProgramList);
                                    downLoadingAdapter.setEmptyView(notDataView);
                                } else {
                                    edit_mine_btn.setVisibility(View.VISIBLE);
                                    ll_mine_pause.setVisibility(View.VISIBLE);
                                    v_spilt_pause.setVisibility(View.VISIBLE);
                                    downingPrograms.clear();
                                    downingPrograms.addAll(downloadProgramList);
                                    downLoadingAdapter.setNewData(downingPrograms);
                                }
                                if (valueCallback != null) {
                                    boolean isPause = true;
                                    for (DownProgramModel programModel : downingPrograms) {
                                        if (programModel.getStats() != DownProgramModel.STATS_PAUSE) {
                                            isPause = false;
                                            break;
                                        }
                                    }
                                    setAllPause(isPause);
                                    valueCallback.onReceiveValue(isPause);
                                }
                            }
                        });
            } else {
                trl_mine.finishRefreshing();
                edit_mine_btn.setVisibility(View.VISIBLE);
                ll_mine_pause.setVisibility(View.VISIBLE);
                v_spilt_pause.setVisibility(View.VISIBLE);
                downLoadingAdapter.setNewData(downingPrograms);
                if (valueCallback != null) {
                    boolean isPause = true;
                    for (DownProgramModel programModel : downingPrograms) {
                        if (programModel.getStats() != DownProgramModel.STATS_PAUSE) {
                            isPause = false;
                            break;
                        }
                    }
                    setAllPause(isPause);
                    valueCallback.onReceiveValue(isPause);
                }
            }
        } else if (position == 1) {
            final List downloadProgramList = new ArrayList<DownProgramModel>();
            ll_mine_pause.setVisibility(View.GONE);
            v_spilt_pause.setVisibility(View.GONE);
            edit_mine_btn.setVisibility(View.GONE);
            downLoadingAdapter.setNewData(new ArrayList<DownProgramModel>());
            if (downedPrograms.isEmpty()) {
                //mLoadView.startLoading(trl_mine);
                Observable.create(new ObservableOnSubscribe<DownProgramModel>() {
                    @Override
                    public void subscribe(ObservableEmitter<DownProgramModel> e) throws Exception {
                        if (!AppDatabase.getInstance(mContext).isOpen()) {
                            e.onComplete();
                        }
                        DownProgramDao dao = AppDatabase.getInstance(mContext).programDao();
                        List<DownProgramModel> downProgramModels = dao.queryForAll();
                        for (DownProgramModel downProgramModel : downProgramModels) {
                            if (downProgramModel.getStats() == DownProgramModel.STATS_SUCCESS) {
                                e.onNext(downProgramModel);
                            }
                        }
                        e.onComplete();
                    }
                }).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .compose(mFragment.<DownProgramModel>bindToLifecycle())
                        .subscribe(new Observer<DownProgramModel>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(DownProgramModel downProgramModel) {
                                downloadProgramList.add(downProgramModel);
                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onComplete() {
                                trl_mine.finishRefreshing();
                                mLoadView.removeParentView(trl_mine);
                                if (downloadProgramList.isEmpty()) {
                                    edit_mine_btn.setVisibility(View.GONE);
                                    downLoadingAdapter.setNewData(downloadProgramList);
                                    downLoadingAdapter.setEmptyView(notDataView);
                                } else {
                                    edit_mine_btn.setVisibility(View.VISIBLE);
                                    downedPrograms.clear();
                                    downedPrograms.addAll(downloadProgramList);
                                    downLoadingAdapter.setNewData(downedPrograms);
                                }
                            }
                        });
            } else {
                trl_mine.finishRefreshing();
                edit_mine_btn.setVisibility(View.VISIBLE);
                downLoadingAdapter.setNewData(downedPrograms);
            }
        }
    }

    public void updateDownProgram(DownProgramModel downProgramModel) {
        if (currentSubTabSelect == 0) {
            if (downProgramModel.getStats() != DownProgramModel.STATS_SUCCESS) {
                int position = 0;
                boolean isChange = false;
                for (int i = 0; i < downingPrograms.size(); i++) {
                    DownProgramModel programModel = downingPrograms.get(i);
                    if (programModel.getDownloadUrl().equals(downProgramModel.getDownloadUrl())) {
                        if (programModel.getStats() != downProgramModel.getStats()) {
                            isChange = true;
                        }
                        programModel.setStats(downProgramModel.getStats());
                        programModel.setDownloadLocationTs(downProgramModel.getDownloadLocationTs());
                        programModel.setDownloadLocation(downProgramModel.getDownloadLocation());
                        programModel.setDownloadStatus(downProgramModel.getDownloadStatus());
                        programModel.setSize(downProgramModel.getSize());
                        position = i;
                        break;
                    }
                }
                downLoadingAdapter.notifyItemChanged(position);
                if (isChange) {
                    boolean isPause = true;
                    for (DownProgramModel programModel : downingPrograms) {
                        if (programModel.getStats() != DownProgramModel.STATS_PAUSE) {
                            isPause = false;
                            break;
                        }
                    }
                    setAllPause(isPause);
                    if (isAllPause()) {
                        btnView.setImageResource(R.mipmap.mine_play_nor);
                        all_text.setText("全部开始");
                    } else {
                        btnView.setImageResource(R.mipmap.mine_pause_nor);
                        all_text.setText("全部暂停");
                    }
                }
            } else {
                updateDownProgram();
            }
        }
    }

    public void updateDownProgram() {
        if (currentSubTabSelect == 0) {
            downedPrograms.clear();
            downingPrograms.clear();
            bindSubscriptData(new ValueCallback<Boolean>() {
                @Override
                public void onReceiveValue(Boolean value) {
                    if (isAllPause()) {
                        btnView.setImageResource(R.mipmap.mine_play_nor);
                        all_text.setText("全部开始");
                    } else {
                        btnView.setImageResource(R.mipmap.mine_pause_nor);
                        all_text.setText("全部暂停");
                    }
                }
            });
        }
    }

    public void changeDelete() {
        downLoadingAdapter.setDelete(!downLoadingAdapter.isDelete());
        downLoadingAdapter.notifyDataSetChanged();
    }

    public boolean isDelete() {
        return downLoadingAdapter.isDelete();
    }

    public boolean isSelectAll() {
        return downLoadingAdapter.isSelectAll();
    }

    public boolean isAllPause() {
        return isAllPause;
    }

    /**
     * 改变状态
     */
    public boolean changePause() {
        setAllPause(!isAllPause);
        List<String> m3u8Urls = new ArrayList<>();
        for (Object o : downingPrograms) {
            if (o instanceof DownProgramModel) {
                DownProgramModel downProgramModel = (DownProgramModel) o;
                if (isAllPause) {
                    if (downProgramModel.getStats() == DownProgramModel.STATS_DOWNLOADING
                            || downProgramModel.getStats() == DownProgramModel.STATS_WAIT
                            || downProgramModel.getStats() == DownProgramModel.STATS_DEFAULT) {
                        m3u8Urls.add(downProgramModel.getDownloadUrl());
                    }
                } else {
                    if (downProgramModel.getStats() == DownProgramModel.STATS_PAUSE) {
                        m3u8Urls.add(downProgramModel.getDownloadUrl());
                    }
                }
            }
        }
        if (isAllPause) {
            DownloadM3u8Controller.getInstance().pauseAll(mContext, m3u8Urls);
        } else {
            if (!AccountHelper.getInstance().isLogin(mContext)) {
                ToastUtil.show(mContext, "用户未登录", Toast.LENGTH_LONG);
                return false;
            }
            if (!NetworkHelper.getInstance().hasConnection(mContext)) {
                ToastUtil.show(mContext, R.string.nointernet, Toast.LENGTH_LONG);
                return false;
            }
            if (NetworkHelper.getInstance().isConnection4g(mContext)
                    && !SharePrefUtil.getDownloadChoose(mContext)) {
                ToastUtil.show(mContext, R.string.download_4g, Toast.LENGTH_LONG);
                return false;
            }
            DownloadM3u8Controller.getInstance().startAll(mContext, m3u8Urls);
        }
        return true;
    }

    public void setAllPause(boolean allPause) {
        isAllPause = allPause;
    }

    public void changeSelectAll() {
        downLoadingAdapter.setSelectAll(!isSelectAll());
    }

    public void deleteSelect() {
        final List<DownProgramModel> downProgramModels = downLoadingAdapter.getDeleteDatas();
        ThreadHelper.post(ThreadHelper.THREAD_WORK, new Runnable() {
            @Override
            public void run() {
                if (downProgramModels.isEmpty()) {
                    ToastUtil.show(mContext, "选择要删除的节目");
                } else {
                    DialogFragmentHelper.showLoadingDialog(mFragment.getChildFragmentManager());
                    DownProgramDao dao = AppDatabase.getInstance(mContext).programDao();
                    //DownProgramDao dao = new DownProgramDao(mContext);
                    TsDao tsDao = AppDatabase.getInstance(mContext).tsDao();
                    for (DownProgramModel downProgramModel : downProgramModels) {
                        if (!TextUtils.isEmpty(downProgramModel.getBasePath())) {
                            deleteDir(downProgramModel.getBasePath());
                            dao.delete(downProgramModel);
                        }
                        List<TsProgramModel> tsProgramModels = tsDao.getTsFromProgram(downProgramModel.getId());
                        for (TsProgramModel tsProgramModel : tsProgramModels) {
                            tsDao.delete(tsProgramModel);
                        }
                    }
                }
            }
        }, new Runnable() {
            @Override
            public void run() {
                if (!downProgramModels.isEmpty()) {
                    DialogFragmentHelper.closeLoadingDialog(mFragment.getChildFragmentManager());
                    downingPrograms.clear();
                    downedPrograms.clear();
                    bindSubscriptData(currentSubTabSelect, new ValueCallback<Boolean>() {
                        @Override
                        public void onReceiveValue(Boolean value) {
                            if (isAllPause()) {
                                btnView.setImageResource(R.mipmap.mine_play_nor);
                                all_text.setText("全部开始");
                            } else {
                                btnView.setImageResource(R.mipmap.mine_pause_nor);
                                all_text.setText("全部暂停");
                            }
                        }
                    });
                }
            }
        });
    }

    //删除文件夹和文件夹里面的文件
    public static void deleteDir(final String pPath) {
        File dir = new File(pPath);
        deleteDirWihtFile(dir);
    }

    public static void deleteDirWihtFile(File dir) {
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;
        for (File file : dir.listFiles()) {
            if (file != null) {
                if (file.isFile())
                    file.delete(); // 删除所有文件
                else if (file.isDirectory())
                    deleteDirWihtFile(file); // 递规的方式删除文件夹
            }
        }
        dir.delete();// 删除目录本身
    }

    @Override
    public void onCheckedAllChanged(boolean stats) {
        if (stats) {
            tv_mine_select.setText("取消全选");
        } else {
            tv_mine_select.setText("全选");
        }
    }

    public void setDeteleView(TextView deteleView) {
        this.tv_mine_select = deteleView;
    }

    public void setBtnView(ImageView btnView, TextView all_text) {
        this.btnView = btnView;
        this.all_text = all_text;
    }
}
